<script setup>
import {
  ref,
  onMounted,
  computed,
  reactive,
  watch,
  nextTick,
  onUnmounted,
  inject,
} from "vue";

import {
  SaveOutlined,
  SendOutlined,
  EditOutlined,
  CopyOutlined,
  LoadingOutlined,
  SyncOutlined,
  VerticalAlignBottomOutlined,
} from "@ant-design/icons-vue";
import store from "@/store";
import request from "@/common/utils/request";

// 保存到文案库弹窗
import BatchCollect from "@/views/shotstack/AiCreation/components/batchCollect.vue";
const BatchCollectRef = ref(null);

import { useRouter, useRoute } from "vue-router";
import { message } from "ant-design-vue";
const router = useRouter();
const route = useRoute();

const props = defineProps({
  // 是否展示小标题
  showTitle: {
    type: Boolean,
    default: true,
  },
  // 是否展示换一换
  showChangeItem: {
    type: Boolean,
    default: true,
  },
});

// 接受父组件数据
const fetchData = inject("fetchData");

// 接受项目id方法
const getImitation_id = inject("getImitation_id");

// 判断是否为组件模式
const isComponents = inject("isComponents");

const isonece = inject("isonece");

// 传递给父组件数据的方法
const getTextArr = inject("getTextArr");

// 获取查详情的id, 组件在不同位置, 取值不同
const getDetailId = () => {
  // 有换一换, 代表在首页, 创建页面
  if (props.showChangeItem) {
    return getImitation_id();
  } else {
    return route.query.id;
  }
};

const state = reactive({
  // 是否全选
  checkAll: false,
  // 是否有已选项
  indeterminate: false,
  // 是否开启违禁词检测
  forbiddenWord: false,
  list: [],
});
// 保存至文案库需要的数据
const chooseTextArticle = ref([]);

// 全部勾选的id
const selectIds = computed(() => {
  // 有数据, 并且 不是全部loding状态
  if (!state.list.length || state.list.every((ele) => ele.loding))
    return {
      ids: [],
      items: [],
    };

  let arr = state.list.reduce(
    (acc, item) => {
      if (item.checked) {
        acc.ids.push(item.id);
        acc.items.push(JSON.parse(JSON.stringify(item)));
      }
      return acc;
    },
    {
      ids: [],
      items: [],
    }
  );
  return arr;
});

// 有loding 或者 有内容为空, 或者标题为空的项
const someEmpty = computed(() => {
  if (!state.list.length)
    return {
      text: "暂无内容",
      disabled: true,
    };
  const someEmpty_loding = state.list.some((ele) => ele.loding);
  if (someEmpty_loding) {
    return {
      text: "请等待生成完成",
      disabled: true,
    };
  }

  const someEmpty_content = state.list.some((ele) => !ele.content.trim());
  if (someEmpty_content) {
    return {
      text: "内容不能为空",
      disabled: true,
    };
  }
  const someEmpty_title = state.list.some((ele) => !ele.title.trim());
  if (someEmpty_title) {
    return {
      text: "标题不能为空",
      disabled: true,
    };
  }
  return {
    text: "",
    disabled: false,
  };
});

// 列表初始赋值
const setList = (list) => {
  state.list = JSON.parse(JSON.stringify(list));
};

// 单独某项勾选改变
const selectChange = (item) => {
  console.log(item.checked, "勾选之后");
  const checkAll = state.list.every((ele) => ele.checked);
  const someChecked = state.list.some((ele) => ele.checked);
  state.checkAll = checkAll;
  // 没有全选, 但是有部分勾选
  if (!checkAll && someChecked) {
    state.indeterminate = true;
  } else {
    state.indeterminate = false;
  }
};

// 全选逻辑
const onCheckAllChange = (e) => {
  // 全部在轮询, 直接无效
  if (state.list.every((ele) => ele.loding)) {
    state.indeterminate = false;
    state.checkAll = false;
    return;
  }
  // 有在轮询中的, 开启半选
  if (state.list.some((ele) => ele.loding)) {
    state.indeterminate = true;
  } else {
    state.indeterminate = false;
  }
  state.list.forEach((ele) => {
    !ele.loding && (ele.checked = state.checkAll);
  });
};

const copyItem = ref(null);

// 开启编辑标题
const editTitle = (item) => {
  copyItem.value = JSON.parse(JSON.stringify(item));
  item.titleEdit = true;
  nextTick(() => {
    const inputDom = document.getElementById("input_" + item.id);
    inputDom && inputDom.focus();
  });
};

// 标题失焦
const inputBlur = (item, index) => {
  if (!item.title.trim()) {
    state.list[index] = JSON.parse(JSON.stringify(copyItem.value));
  }
  state.list[index].titleEdit = false;
};

const setItem = (data) => {
  if (data.type == "add") {
    // 纯添加一个占位符
    state.list.push(JSON.parse(JSON.stringify(data.item)));
    console.log("子组件传递的方法被调用", data);
    nextTick(() => {
      const element = document.getElementById("TextImitation_list");
      !!element &&
        element.scrollTo({
          top: element.scrollHeight,
          behavior: "smooth", // 平滑滚动
        });
    });
  } else if (data.type == "removeAndAdd") {
    // 删除占位符, 如果传递过来了新的项, 则添加新的项
    const index = state.list.findIndex((ele) => ele.id == data.delId);
    state.list.splice(index, 1);
    data?.item && state.list.push(JSON.parse(JSON.stringify(data.item)));
  } else if (data.type == "update") {
    console.log(data, "update");

    // 找到对应的项, 更新内容
    const index = state.list.findIndex((ele) => ele.id == data.item.id);
    index != -1 && Object.assign(state.list[index], data.item);
  }
};

// 去一键成片
const toOneClickClip = (id) => {
  router.push({
    name: "OneClickClip",
    query: {
      itemId: id,
      imitation_id: getDetailId(),
    },
  });
};

// 批量导入进一键成片
const bulkImport = () => {
  console.log(selectIds.value.ids, "勾选的项");
  if (!selectIds.value.ids.length) return;
  if (selectIds.value.ids.length > 5)
    message.success("一键成片最多可以导入五条脚本, 已自动为您去除多余的选项");
  router.push({
    name: "OneClickClip",
    query: {
      itemId: selectIds.value.ids.slice(0, 5),
      imitation_id: getDetailId(),
    },
  });
};

// 保存到文案库
const saveToTextlibrary = (item) => {
  chooseTextArticle.value = [
    {
      title: item.title,
      content: item.content,
      sub_title: "",
    },
  ];

  BatchCollectRef.value.showModal();
};

// 保存至混剪
const saveToHunjian = (item) => {
  let data = [];
  data.push(item.content);
  store.commit("SET_SCENE_CREATION_TEXTS", data);

  router.push({
    name: "mixedCutCreat",
    query: { type: 0, viewType: 2, Textlibrary: "Textlibrary" },
  });
};

// 保存编辑和修改
const saveChange = async (showMsg = true) => {
  const result_content = state.list.map((ele) => {
    return {
      id: ele.id,
      title: ele.title,
      subtitle_text_block: [ele.content],
    };
  });

  // 获取完列表之后 更新服务器的列表数据
  const res = await request.put(
    "/work_ai",
    "/user/shotstack/scripttext/imitation/update",
    {
      result_content,
      imitation_id: getDetailId(),
    }
  );

  console.log(res, "更新结果");
  showMsg && message.success("保存成功!");
};

// 批量剪辑
const batchTextOperation = () => {

  const sceneCreationTexts = selectIds.value.items?.map((text) => text.content);
  const sceneCreationTitles = selectIds.value.items?.map((text) => text.title);

  // 存放即将导入到混剪的文案数据
  store.commit("SET_SCENE_CREATION_TEXTS", sceneCreationTexts);
  store.commit("SET_SCENE_CREATION_TITLES", sceneCreationTitles);

  router.push({
    name: "mixedCutCreat",
    query: { type: 0, viewType: 2, TextImitation: "TextImitation" },
  });
};

// 批量导入到文案库
const bulkSaveToTextlibrary = () => {
  console.log(selectIds.value.ids, "勾选的项");
  if (!selectIds.value.ids.length) return;

  chooseTextArticle.value = selectIds.value.items.map((ele) => {
    return {
      title: ele.title,
      content: ele.content,
      sub_title: "",
    };
  });
  BatchCollectRef.value.showModal();
};

// 作为组件使用 - 导入选择的数据
const importItems = () => {
  if (!selectIds.value.ids.length) return;
  console.log(selectIds.value.items, "选择的数据");

  if (isonece && selectIds.value.ids.length > 1) {
    return message.warning("最多导入一条数据");
  }

  getTextArr(JSON.parse(JSON.stringify(selectIds.value.items)));
};
// 作为组件使用, 导入某项数据
const importItem = (item) => {
  console.log(item, "选择的数据");
  getTextArr([JSON.parse(JSON.stringify(item))]);
};

// 父组件调用
const changeItem = () => {
  fetchData(setItem, saveChange);
};

// 动态获取该组件的列表数据
const list = computed(() => {
  return state.list;
});

// 批量保存至文案库
const saveLibrary = () => {
  chooseTextArticle.value = state.list.map((item) => {
    return {
      title: item.title,
      content: item.content,
      sub_title: "",
    };
  });
  BatchCollectRef.value.showModal();
};

defineExpose({
  setList,
  list,
});
</script>

<template>
  <div class="TextListContent" v-if="!!state.list.length">
    <!-- <a-button @click="changeItem"> 祖孙通信 </a-button> -->
    <div class="content_title">
      <div class="title_left">
        <a-checkbox
          v-model:checked="state.checkAll"
          :indeterminate="state.indeterminate"
          @change="onCheckAllChange"
          :disabled="state.list.every((ele) => ele.loding)"
        >
          全选
        </a-checkbox>
      </div>

      <div class="title_right">
        <!-- <div class="forbiddenWord">
          <a-switch v-model:checked="state.forbiddenWord" />
          <span
            class="forbiddenWord_text"
            @click="state.forbiddenWord = !state.forbiddenWord"
            >违禁词检测</span
          >
        </div> -->
        <template v-if="!isComponents">
          <a-button
            type="default"
            :disabled="!selectIds.ids.length"
            @click="bulkSaveToTextlibrary"
          >
            <SaveOutlined />
            批量保存到文案库</a-button
          >
          <a-button
            type="primary"
            :disabled="!selectIds.ids.length"
            @click="batchTextOperation"
          >
            <SendOutlined />
            批量剪辑</a-button
          >
          <a-button
            type="primary"
            :disabled="!selectIds.ids.length"
            @click="bulkImport"
            v-permissionOneClickClip
          >
            <SendOutlined />
            批量成片</a-button
          >
          <template v-if="someEmpty.disabled">
            <a-tooltip placement="top">
              <template #title>
                <span>{{ someEmpty.text }}</span>
              </template>
              <a-button type="primary" :disabled="true">
                <SaveOutlined />
                保存修改</a-button
              >
            </a-tooltip>
          </template>

          <!-- v-else -->
          <a-button type="primary" v-else @click="saveChange">
            <SaveOutlined />
            保存修改</a-button
          >
        </template>

        <template v-else>
          <a-button
            type="primary"
            :disabled="!selectIds.ids.length"
            @click="saveLibrary"
          >
            <SaveOutlined />
            批量保存至文案库
          </a-button>
          <a-button
            v-if="!isonece"
            type="primary"
            :disabled="!selectIds.ids.length"
            @click="importItems"
          >
            <SendOutlined />
            批量导入文案</a-button
          >
        </template>
      </div>
    </div>

    <div class="content_list" id="TextImitation_list">
      <!-- props.showTitle -->
      <div
        class="number_title_box"
        v-if="props.showTitle && !!state.list.length"
      >
        <h2>生成{{ state.list.length }}篇文章</h2>
        <span>由营销算法加强生成</span>
      </div>

      <div
        class="content_list_item"
        v-for="(item, index) in state.list"
        :key="item.id"
      >
        <div class="item_title">
          <a-checkbox
            v-model:checked="item.checked"
            @change="selectChange(item)"
            :disabled="item.loding"
          />

          <template v-if="!item.titleEdit">
            <p class="item_title_text">
              {{ `NO.${index + 1} ` + item.title }}
              <EditOutlined @click="editTitle(item)" v-if="!item.loding" />
            </p>
          </template>
          <template v-else>
            <a-input
              @blur="inputBlur(item, index)"
              :id="'input_' + item.id"
              v-model:value="item.title"
              placeholder="请输入标题"
              size="small"
            />
          </template>
        </div>

        <div class="item_content_box">
          <!-- <template v-else> -->
          <!-- <div class="tags">
              <span class="tag_item" v-for="ele in item.tags" :key="ele.id">{{
                ele.text
              }}</span>
            </div> -->
          <div class="item_content">
            <template v-if="!item.content && item.loding">
              <div class="is_loding">
                <div class="loding_content">
                  <LoadingOutlined />
                  <span> AI正在创作中... </span>
                </div>
              </div>
            </template>

            <template v-else>
              <a-textarea
                v-model:value="item.content"
                placeholder="请输入文案!"
                :auto-size="{ minRows: 5, maxRows: 8 }"
              />
              <div class="text_num_box">
                <span class="text_num"
                  >已生成 {{ item.content.length }} 字</span
                >
              </div>
            </template>

            <div class="item_btns">
              <div class="left_btns">
                <a-button
                  type="link"
                  style="font-size: 13px; margin-right: 10px"
                  @click="$utils.copyText(item.content)"
                  :disabled="item.loding"
                >
                  <CopyOutlined />
                  复制</a-button
                >
                <a-button
                  type="link"
                  style="font-size: 13px"
                  @click="changeItem"
                  :disabled="item.loding"
                  v-if="props.showChangeItem"
                >
                  <SyncOutlined />
                  换一篇</a-button
                >
              </div>

              <template v-if="!isComponents">
                <div class="right_btns">
                  <a-button
                    type="link"
                    style="font-size: 13px"
                    :disabled="item.loding"
                    @click="saveToTextlibrary(item)"
                  >
                    <SaveOutlined /> 保存至文案库</a-button
                  >

                  <a-button
                    type="primary"
                    style="font-size: 13px"
                    :disabled="item.loding"
                    @click="saveToHunjian(item)"
                  >
                    <SendOutlined /> 去剪辑</a-button
                  >
                  <a-button
                    v-permissionOneClickClip
                    type="primary"
                    style="font-size: 13px"
                    :disabled="item.loding"
                    @click="toOneClickClip(item.id)"
                  >
                    <SendOutlined /> 一键成片</a-button
                  >
                </div>
              </template>

              <template v-else>
                <div class="right_btns_components">
                  <a-button
                    type="link"
                    style="font-size: 13px; margin-right: 10px"
                    :disabled="item.loding"
                    @click="saveToTextlibrary(item)"
                  >
                    <SaveOutlined /> 保存至文案库</a-button
                  >
                  <a-button
                    type="link"
                    style="font-size: 13px"
                    :disabled="item.loding"
                    @click="importItem(item)"
                  >
                    <VerticalAlignBottomOutlined /> 导入文案</a-button
                  >
                </div>
              </template>
            </div>
          </div>
          <!-- </template> -->
        </div>
      </div>
    </div>
  </div>

  <BatchCollect
    ref="BatchCollectRef"
    :articles="chooseTextArticle"
  ></BatchCollect>
</template>

<style lang="less" scoped>
@text_color: #2b2b3d;
.TextListContent {
  width: 100%;
  height: 100%;
  padding: 15px 20px;
  display: flex;
  flex-direction: column;
  color: @text_color;

  // 列表项
  .content_list {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 20px;
    overflow-y: auto;
    padding-bottom: 20px;
    &::-webkit-scrollbar {
      width: 8px; /* 滚动条的宽度 */
      height: 10px; /* 滚动条的高度，垂直滚动条可能用得上 */
      // display: none;
    }

    // 标题
    .number_title_box {
      display: flex;
      align-items: center;
      h2 {
        font-size: 16px;
        font-weight: 900;
        margin: 0;
        margin-right: 5px;
      }
      span {
        font-size: 11px;
        color: #575757;
        padding: 1px 8px;
        background: #d6d6d6;
      }
    }

    .content_list_item {
      // 每一项的标题
      .item_title {
        display: flex;
        align-items: center;
        gap: 10px;
        margin-bottom: 10px;
        p {
          margin: 0;
        }
      }
      // 每一项的主体部分
      .item_content_box {
        border: 1px solid #00000023;
        border-radius: 8px;
        padding: 15px;
        padding-bottom: 8px;

        // 加载中
        .is_loding {
          display: flex;
          justify-content: center;
          align-items: center;
          height: 150px;
          .loding_content {
            color: var(--ss-primary-color);
          }
        }
        .item_content {
          .text_num_box {
            display: flex;
            justify-content: end;
            padding: 5px 0;
            .text_num {
              color: #8a8a8a;
              font-size: 13px;
            }
          }

          .item_btns {
            border-top: 1px solid #00000023;
            padding-top: 8px;
            display: flex;
            justify-content: space-between;
            .left_btns {
              :deep(.ss-btn) {
                padding: 0;
                span {
                  margin-left: 3px;
                }
              }
            }

            .right_btns {
              display: flex;
              gap: 10px;
              :deep(.ss-btn) {
                span {
                  margin-left: 4px;
                }
              }
            }
            // 组件化时 才会有的右侧样式
            .right_btns_components {
              :deep(.ss-btn) {
                padding: 0;
                span {
                  margin-left: 3px;
                }
              }
            }
          }
        }
        // 标签
        .tags {
          display: flex;
          gap: 20px;
          margin-bottom: 15px;
          .tag_item {
            border: 1px solid #00000073;
            // background: skyblue;
            // color: rgb(2, 81, 117);
            border-radius: 5px;
            font-size: 12px;
            padding: 1px 8px;
            position: relative;

            &::after {
              content: "+";
              font-size: 18px;
              font-weight: 600;
              right: -17px;
              top: -5px;
              position: absolute;
            }

            &:nth-last-child(1) {
              &::after {
                content: "";
              }
            }
          }
        }
      }
    }
  }

  // 标题控制按钮
  .content_title {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    .title_right {
      display: flex;
      align-items: center;
      gap: 0 15px;
      .forbiddenWord {
        display: flex;
        align-items: center;
        gap: 5px;
        &:hover {
          & .forbiddenWord_text {
            color: var(--ss-primary-color-hover);
          }
        }
        .forbiddenWord_text {
          cursor: pointer;
          transition: all 0.3s;
        }
      }
    }
  }
}
</style>
